package com.hz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hz.dao.SafetyInfoDao;
import com.hz.pojo.SafetyInfo;
import com.hz.pojo.User;
import com.hz.service.SafetyInfoService;
import com.hz.utils.DateUtils;
import com.hz.utils.MassageJsons;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
@Service
public class SafetyInfoServiceImpl implements SafetyInfoService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    SafetyInfoDao safetyInfoDao;
    @Resource
    UserServiceImpl userService;
    @Override
    @Transactional
    public MassageJsons updAccountMoney(String open_id,Double account_money) throws Exception {
        Double money = account_money;


        /*//从Redis查询当前用户的信息
        String userjson = stringRedisTemplate.opsForValue().get(open_id);
        //转换成对象
        User user = JSONObject.parseObject(userjson,User.class);*/
        User user = userService.getUserInfo(open_id);
        //更改用户提现总金额
        safetyInfoDao.updWithdrawMoney(open_id,user.getSafetyInfo().getWithdraw_money()+money);
        //减去提现金额 计算出余额
        account_money = user.getSafetyInfo().getAccount_money()-account_money;
        //执行数据库余额更新方法
        int i = safetyInfoDao.updAccountMoney(open_id,account_money);
        //更新程序收益
        stringRedisTemplate.opsForValue().increment("HN520",-money);
        if(i!=0){
            //添加提现记录
            safetyInfoDao.addWithdrawalInfo(open_id,money,DateUtils.getCurrentTime());
            //查询最新用户信息
            user = userService.getUserInfo(user.getOpen_id());
            //从新存入Redis
            stringRedisTemplate.opsForValue().set(open_id,JSONObject.toJSONString(user));
            return new MassageJsons("0","提现成功",user);
        }else {return new MassageJsons("0","提现失败");}
    }

    @Override
    public SafetyInfo getSafetyInfo(String open_id) throws Exception {
        return safetyInfoDao.getSafetyInfo(open_id);
    }

    @Override
    public int updPayPassword(String open_id, String pay_password) throws Exception {

        return safetyInfoDao.updPayPassword(open_id,pay_password);
    }

}
